package controllers;

import play.*;
import play.mvc.*;
import play.mvc.Scope.RenderArgs;

import java.util.*;

import framework.base.BaseController;
import framework.security.models.SecurityMenu;
import framework.utils.MD5Util;
import framework.utils.SecurityUtil;
import framework.utils.StringUtil;
import models.*;
import models.security.User;
import models.security.utils.SecurityConstant;

public class Application extends BaseController {
    /**
     * 系统首页
     */
    public static void index() {
        if(SecurityUtil.isLogin()){
            main();
        }else{
            render();
        }
    }
    
    /**
     * 用户登录
     */
    public static void login(){
        String userName = StringUtil.trim(params.get("username"));
        String password = StringUtil.trim(params.get("password"));
        String reason=null;
        String userId=null;
        if(StringUtil.isBlank(userName)||StringUtil.isBlank(password)){
            reason="用户名和密码不能为空";
        }else{
            User user = User.findByUserName(userName);
            if(null==user){
                reason="用户不存在";
            }else{
                userId = user.id+"";
                String encryptStr = MD5Util.encodeToStr(StringUtil.trim(password)+StringUtil.trim(user.securityKey));
                if(!encryptStr.equals(user.password)){
                    reason="用户名或密码不正确";
                }else{
                    //用户的登录逻辑
                    Map<String,String> permissions = user.allPermissions();
                    SecurityUtil.loginWithCookie(user.id+"",user.userName, user.name, permissions.get(SecurityConstant.RESOURCE_MENU_TYPE_NAME), permissions.get(SecurityConstant.RESOURCE_ACTION_TYPE_NAME),user.securityKey);
                    String ip = request.current().remoteAddress;
                    user.login(ip);
                }
            }
        }
        if(!StringUtil.isBlank(reason)){
            saveUserLogAndNotice(reason,false);
            render("@index");
        }else{
            main();
        }
    }
    
    /**
     * 系统退出
     */
    public static void logout(){
        SecurityUtil.logout();
        index();
    }
    
    
    /**
     * 系统主页面
     */
    public static void main(){
        render();
    }
    
    @Before(only="Application.main")
    static void requireUser(){
        if(!SecurityUtil.isLogin()){
            index();
        }else{
            SecurityUtil.getSelectedMenu();
            Map<SecurityMenu,List<SecurityMenu>> resources=SecurityUtil.getResources();
            RenderArgs.current().put("resources",resources);
        }
        
    }

}